// 权限控制
import router from './router'
import { getToken } from './utils/auth'
import store from './store'
import { asyncRoutes } from './router'

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

const WHITE_LIST = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = getToken()
  // 有token
  if (token) {
    next()
    // 判断是否获取过用户信息 -> 没有 -> 派发了一个action
    if (!store.state.user.profile.id) {
      // 获取原始权限列表
      console.log('获取原始权限列表')
      const permissions = await store.dispatch('user/getProfile')
      console.log(permissions)
      // 2. 把后端的权限数组格式化成我们自己的俩个权限数据
      const firstRoutePerms = getFirstRoutePerms(permissions)
      console.log(firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(permissions)
      console.log(secondRoutePerms)

      // 3. 根据用户权限点过滤动态路由
      let filterRoutes = []
      if (firstRoutePerms.length === 1 && firstRoutePerms[0] === '*') {
        filterRoutes = asyncRoutes
      } else {
        filterRoutes = asyncRoutes.filter(item => {
          return firstRoutePerms.includes(item.permission)
        }).map(item => {
          return {
            ...item,
            children: item.children.filter(child => {
              return secondRoutePerms.includes(child.permission)
            })
          }
        })
      }
      console.log('过滤后的路由', filterRoutes)
      // 4. addRoutes动态添加
      filterRoutes.forEach(route => {
        router.addRoute(route)
      })
      // 5. 存入Vuex渲染左侧菜单
      store.commit('menu/setMenuList', filterRoutes)
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
